package com.dctp.ems.controller.chart;

import com.dctp.common.cache.ContractCache;
import com.dctp.common.controller.BaseController;
import com.dctp.common.db.ContractDb;
import com.dctp.common.utils.CollectUtil;
import com.dctp.common.vo.JsonResult;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.core.Path;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Path("/chart/contractStat")
public class ContractStatController extends BaseController {

    /**
     * 查询所有合约的五个维度统计，自动根据角色权限过滤
     */
    public void index() {
        String filterField = getFilterField();  // 例如: bottom_role_user_id
        StringBuilder sql = new StringBuilder();
        List<Object> params = new ArrayList<>();

        sql.append(
                "SELECT symbol, " +
                        "COUNT(DISTINCT user_id) AS user_count, " +
                        "SUM(quantity) AS quantity, " +
                        "SUM(margin_occupied) AS margin, " +
                        "SUM(IFNULL(realized_pnl, 0)) AS pnl, " +
                        "SUM(open_service_fee + IFNULL(close_service_fee,0)) AS fee " +
                        "FROM dctp_order WHERE status=1 "
        );

        // 权限过滤
        if (filterField != null) {
            Object value = getRequestUser().get("id");
            sql.append("AND ").append(filterField).append(" = ? ");
            params.add(value);
        }

        sql.append("GROUP BY symbol ORDER BY quantity DESC");

        List<Record> list = Db.find(sql.toString(), params.toArray());
        if (CollectUtil.isNotEmpty(list)) {
            for (Record record : list) {
                record.set("name", ContractCache.getNameBySymbol(record.get("symbol")));
            }
        }
        renderJson(JsonResult.successWithData(CollectUtil.convert(list,Record::toMap)));
    }


    public void dyn() {
        String filterField = getFilterField();
        StringBuilder sql = new StringBuilder();
        List<Object> params = new ArrayList<>();

        sql.append(
                "SELECT symbol, " +
                        "COUNT(DISTINCT user_id) AS user_count, " +
                        "SUM(quantity) AS quantity, " +
                        "SUM(margin_occupied) AS margin, " +
                        "SUM(IFNULL(realized_pnl, 0)) AS pnl, " +
                        "SUM(open_service_fee + IFNULL(close_service_fee,0)) AS fee " +
                        "FROM dctp_order WHERE status=1 "
        );

        if (filterField != null) {
            Object value = getRequestUser().get("id");
            sql.append("AND ").append(filterField).append(" = ? ");
            params.add(value);
        }

        sql.append("GROUP BY symbol");

        List<Record> stats = Db.find(sql.toString(), params.toArray());

        // 转换成map方便查找
        Map<String, Record> statMap = new HashMap<>();
        if (CollectUtil.isNotEmpty(stats)) {
            for (Record record : stats) {
                statMap.put(record.getStr("symbol"), record);
            }
        }

        // 查询所有合约
        List<String> allSymbols = ContractDb.findAll().stream().map(item -> item.getStr("symbol")).toList();
        List<Record> resultList = new ArrayList<>();

        for (String symbol : allSymbols) {
            Record record = statMap.get(symbol);
            if (record == null) {
                record = new Record()
                        .set("symbol", symbol)
                        .set("user_count", 0)
                        .set("quantity", BigDecimal.ZERO)
                        .set("margin", BigDecimal.ZERO)
                        .set("pnl", BigDecimal.ZERO)
                        .set("fee", BigDecimal.ZERO);
            }
            record.set("name", ContractCache.getNameBySymbol(symbol));
            resultList.add(record);
        }
        renderJson(JsonResult.successWithData(CollectUtil.convert(resultList, Record::toMap)));
    }
}
